package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojo.WmUser;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealNameMapper;
import com.heima.user.service.ApUserRealNameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper, ApUserRealname> implements ApUserRealNameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1.校验
        dto.checkParam();
        //2.分页查询
        IPage<ApUserRealname> pageReq = new Page<ApUserRealname>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQuery = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            lambdaQuery.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        //3.查询
        IPage<ApUserRealname> result = this.page(pageReq, lambdaQuery);

        //4.封装返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal());
        responseResult.setData(result.getRecords());
        return responseResult;
    }

    @Autowired
    private ApUserMapper apUserMapper;
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1.检查参数
        Integer id = dto.getId();
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户id不存在");
        }
        //2.检查用户信息是否存在
        ApUserRealname realName = this.getById(id);
        if (null==realName){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //3.判断审核状态
        if (realName.getStatus()!= AdminConstants.WAIT_AUTH) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该信息不为待审核状态");
        }
        //4.关联userId查询Ap_user的信息
        Integer userId = realName.getUserId();
        ApUser apUser = apUserMapper.selectById(userId);
        if(apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的用户信息不存在");
        }
        // 更新实名认证的状态,原因
        realName.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            realName.setReason(dto.getMsg());
        }
        updateById(realName);
        if(status.equals(AdminConstants.PASS_AUTH) ){
            WmUser wmUser = createWmUser(apUser);
            if(wmUser == null || wmUser.getId() == null){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"创建自媒体账户信息失败");
            }
            ResponseResult responseResult = createApAuthor(wmUser);
            if(responseResult.getCode() != 0){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR,responseResult.getErrorMessage());
            }
        }
        //int i = 1/0;
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;

    /**
     * 远程创建作者信息
     * @param wmUser
     * @return
     */
    private ResponseResult createApAuthor(WmUser wmUser) {
        // 查询 ap_user_id相关联的作者信息 是否存在
        ApAuthor author = articleFeign.findByUserId(wmUser.getApUserId());
        if(author!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"关联的作者信息已经存在");
        }
        // 创建作者信息
        author = new ApAuthor();
        author.setName(wmUser.getName());
        author.setType(2);
        author.setUserId(wmUser.getApUserId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        return articleFeign.save(author);
    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 远程创建自媒体账户
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 远程查询自媒体账户
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if(wmUser!=null){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"自媒体账户已经存在");
        }
        // 如果不存在，创建自媒体账号
        wmUser = new WmUser();
        BeanUtils.copyProperties(apUser,wmUser);
        wmUser.setId(null);
        wmUser.setApUserId(apUser.getId());
        return wemediaFeign.save(wmUser); // 保存成功后 返回的wmUser携带了 id
    }
}

